<template>
  <div class="blog-list">
    <div class="header">
      <h1>技术文章</h1>
      <div class="button-group">
        <a-button
          type="primary"
          @click="$router.push({ path: '/profile', query: { tab: 'blogs' } })"
          style="margin-right: 10px"
        >
          我的文章
        </a-button>
        <a-button
          type="primary"
          @click="$router.push('/blogs/create')"
        >
          发表文章
        </a-button>
      </div>
    </div>
    <a-spin :spinning="loading">
        <template v-if="!loading">
          <div v-if="error" class="error-container">
            <a-alert
              :message="error"
              type="error"
              show-icon
              style="margin-bottom: 20px"
            />
            <a-button type="primary" @click="handleRetry">重试</a-button>
          </div>
          <template v-else>
            <BlogList :blogs="blogs" @blog-click="onBlogClick" />
            <a-pagination
              v-model:current="currentPage"
              :pageSize="pageSize"
              :total="total"
              @change="fetchBlogs"
              style="margin-top: 30px; text-align: center"
            /> 
          </template>
        </template>
    </a-spin>
  </div>
</template>

<script>
import { useBlogStore } from '@/stores/blog'
import { message } from 'ant-design-vue'
import BlogList from '@/components/BlogList.vue'
export default {
  name: 'BlogView',
  components: { BlogList },
  data() {
    const blogStore = useBlogStore()
    return {
      loading: false,
      error: null,
      blogStore,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      blogs: []
    }
  },
  created() {
    this.fetchBlogs()
  },
  methods: {
    async fetchBlogs() {
      this.loading = true
      this.error = null
      try {
        const { blogs, total } = await this.blogStore.fetchBlogList({
          page: this.currentPage,
          pageSize: this.pageSize
        })
        this.blogs = blogs?.map(blog => ({
          ...blog
        })) || []
        this.total = total || 0
      } catch (error) {
        this.error = error.message || '加载失败，请重试'
        message.error(this.error)
      } finally {
        this.loading = false
      }
    },
    handleRetry() {
      this.fetchBlogs()
    },
    onBlogClick(blog) {
      this.$router.push(`/blogs/${blog.id}`)
    }
  }
}
</script>

<style scoped>
.blog-list {
  padding: 20px;
  width: 60%;
  margin: 0 20%;
}

.blog-list .header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.error-container {
  text-align: center;
  padding: 20px;
}
</style>